@echo off
REM /**
REM  * @file buildcert.bat
REM  * 
REM  * Batch file to generate secure boot keys.
REM  * 
REM  * @author https://ay123.net 
REM  * @version 0.1
REM  * @date 2024-03-02
REM  * 
REM  * @copyright Copyright (c) 2015 - 2024
REM  * 
REM  */

SET OPENSSL_CONF=.\tools\openssl\openssl.cnf
SET openssl=.\tools\openssl\openssl.exe

REM 定义密钥和证书的存储位置
SET KEYS_PATH=.\keys
mkdir %KEYS_PATH%

REM 设置证书信息

REM 确保存储位置存在
if not exist %KEYS_PATH% mkdir %KEYS_PATH%;

REM 设置密钥和证书的有效期（天数）
SET VALIDITY_PERIOD=3650

echo Generating Platform Key (PK)...
%openssl% genrsa -out "%KEYS_PATH%\PK.key" 2048
%openssl% req -new -x509 -key "%KEYS_PATH%\PK.key" -out "%KEYS_PATH%\PK.crt" -days %VALIDITY_PERIOD% -subj "/CN=AY123 PK/OU=AY123.NET"

echo Generating Key Exchange Key (KEK)...
%openssl% genrsa -out "%KEYS_PATH%\KEK.key" 2048
%openssl% req -new -key "%KEYS_PATH%\KEK.key" -out "%KEYS_PATH%\KEK.csr" -subj "/CN=AY123 KEK/OU=AY123.NET"

echo Generating Signature Database Key (DB)...
%openssl% genrsa -out "%KEYS_PATH%\DB.key" 2048
%openssl% req -new -key "%KEYS_PATH%\DB.key" -out "%KEYS_PATH%\DB.csr" -subj "/CN=AY123 DB/OU=AY123.NET"

echo Signing Key Exchange Key (KEK) with Platform Key (PK)...
%openssl% x509 -req -in "%KEYS_PATH%\KEK.csr" -CA "%KEYS_PATH%\PK.crt" -CAkey "%KEYS_PATH%\PK.key" -CAcreateserial -out "%KEYS_PATH%\KEK.crt" -days %VALIDITY_PERIOD%

echo Signing Signature Database Key (DB) with Key Exchange Key (KEK)...
%openssl% x509 -req -in "%KEYS_PATH%\DB.csr" -CA "%KEYS_PATH%\KEK.crt" -CAkey "%KEYS_PATH%\KEK.key" -CAcreateserial -out "%KEYS_PATH%\DB.crt" -days %VALIDITY_PERIOD%

echo Converting PEM to DER format...
%openssl% x509 -outform der -in "%KEYS_PATH%\PK.crt" -out  "%KEYS_PATH%\PK.cer"
%openssl% x509 -outform der -in "%KEYS_PATH%\KEK.crt" -out "%KEYS_PATH%\KEK.cer"
%openssl% x509 -outform der -in "%KEYS_PATH%\DB.crt" -out  "%KEYS_PATH%\DB.cer"


%openssl% pkcs12 -export -out "%KEYS_PATH%\DB.pfx" -inkey "%KEYS_PATH%\DB.key" -in "%KEYS_PATH%\DB.crt" -password pass:YourPfxPassword


echo Generation of Secure Boot Keys completed.